package com.adnaan.backend.common.config;

import com.adnaan.backend.common.interceptor.AuthInterceptor;
import com.adnaan.backend.common.utils.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * author: adnaan
 * create: 2023-11-29 14:29
 * Description: 自定义拦截器
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Value("${car.profile}")
    private String UPLOAD_FOLDER;
    /**
     * 注入自定义拦截器
     */
    @Resource
    private AuthInterceptor authInterceptor;

    /**
     * 配置拦截器和拦截、放行路径
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // excludePathPatterns放行路径，addPathPatterns拦截的路径
        registry.addInterceptor(authInterceptor)
                .excludePathPatterns("/api/login/**","/api/screen/**", "/profile/**", "/swagger**/**", "/v3/**")
                .addPathPatterns("/**");
    }


    /**
     * 求路径和服务器上的路径进行对应
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /* 本地文件上传路径 */
        registry.addResourceHandler(Constant.RESOURCE_PREFIX + "/**")
                .addResourceLocations("file:" + UPLOAD_FOLDER + "/");
    }

    /*解决跨域问题*/
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/screen/**") // 允许跨域访问的路径
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}

